//
//  ViewController.m
//  sinashebao
//
//  Created by  androidlongs on 2017/11/28.
//  Copyright © 2017年  androidlongs. All rights reserved.
//

#import "ViewController.h"
#import "SINALoginViewController.h"
#import "SINANavLoginViewController.h"
#import "SINAStudentMainViewController.h"
#import "SINATeacherMainViewController.h"
#import "SINAStudentTabBarViewController.h"
#import "SINATeacherTabBarViewController.h"
#import "SINAControllerUtils.h"
#import <AMapFoundationKit/AMapFoundationKit.h>

#import "PTStudentLifeServiceViewController.h"
#import "AppDelegate.h"

#define KYRect [UIScreen mainScreen].bounds


@interface ViewController ()<UIScrollViewDelegate>
{
    UIPageControl * pageControl;
    UIScrollView * welcomeScrollView;
    UIButton * startIn;
}
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (strong,nonatomic) NSTimer *timer;
@property (assign,nonatomic) NSInteger indexTime;

@property (weak, nonatomic) IBOutlet UIImageView *appIconImageView;
@property (weak, nonatomic) IBOutlet UILabel *appIconLabel;
@property (weak, nonatomic) IBOutlet UILabel *appIconFlagLabel;
@property (weak, nonatomic) IBOutlet UIImageView *mainImageView;
@property (weak, nonatomic) IBOutlet UILabel *sloganLabel;

@property(nonatomic) BOOL isLoading;
@property(nonatomic) BOOL isTimeLoading;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //如果是首次启动，则显示引导页，否则显示广告页
    
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    
    NSNumber * notFirstStart = [userDefaults objectForKey:@"NOT_FIRST_START"];
    
    if ([notFirstStart boolValue]==NO) {
        
        self.timeLabel.hidden = YES;
        self.appIconImageView.hidden = YES;
        self.appIconLabel.hidden = YES;
        self.appIconFlagLabel.hidden= YES;
        self.mainImageView.hidden = YES;
        self.sloganLabel.hidden = YES;
       
        [self createWelcomeView];
    }
    else
    {
        self.timeLabel.hidden = NO;
        self.appIconImageView.hidden = NO;
        self.appIconLabel.hidden = NO;
        self.appIconFlagLabel.hidden=  NO;
        self.mainImageView.hidden = NO;
        self.sloganLabel.hidden = NO;
        
        [self initConfigFunction];
        [self initViewFunction];
    }
}

-(void)createWelcomeView
{
    CGRect rect = self.view.bounds;
    
    welcomeScrollView = [[UIScrollView alloc]initWithFrame:rect];
    welcomeScrollView.pagingEnabled = YES;
    welcomeScrollView.showsVerticalScrollIndicator = NO;
    welcomeScrollView.showsHorizontalScrollIndicator = NO;
    welcomeScrollView.contentSize = CGSizeMake(rect.size.width * 4,rect.size.height);
    welcomeScrollView.bounces = NO;  //不需要弹簧效果
    welcomeScrollView.delegate = self;
    welcomeScrollView.backgroundColor =PNColor(250, 250, 250);
    [self.view addSubview:welcomeScrollView];
    
    NSArray * arr = [NSArray arrayWithObjects:@"welcome01",@"welcome02",@"welcome03",@"welcome04", nil];
    
    for (int i =0; i<arr.count; i++) {
        
        UIImage * img = [UIImage imageNamed:[arr objectAtIndex:i]];
        
        UIImageView * imgView = [[UIImageView alloc]initWithFrame:CGRectMake((i*rect.size.width) + (rect.size.width - img.size.width)/2, rect.origin.y + (Height_NavBar)  + 10, img.size.width, img.size.height)];
        [imgView setImage:img];
        imgView.backgroundColor = [UIColor clearColor];
        [welcomeScrollView addSubview:imgView];
        
        if (IS_IPHONE_X) {
            
            [imgView setFrame:CGRectMake((i*rect.size.width) + (rect.size.width - img.size.width)/2, rect.origin.y + (Height_NavBar)  + 40, img.size.width, img.size.height)];
        }
    }
    
//    NSLog(@"%.2f",Height_TabBar);
    //当添加到最后一个时，添加立即体验按钮
    startIn = [UIButton buttonWithType:UIButtonTypeCustom];
    [startIn setTitle:@"立即体验" forState:UIControlStateNormal];
    [startIn setTitleColor:PNColor(52, 158, 247) forState:UIControlStateNormal];
    startIn.layer.cornerRadius = 20;
    startIn.layer.borderWidth = 1.5;
    startIn.layer.borderColor =PNColor(52, 158, 247).CGColor;
    startIn.titleLabel.font = [UIFont systemFontOfSize:18];
    [startIn setFrame:CGRectMake((rect.size.width * 3) + (rect.size.width- 130)/2,rect.size.height - (Height_TabBar) - 20 , 130, 40)];
    [startIn addTarget:self action:@selector(onClickStartInButton:) forControlEvents:UIControlEventTouchUpInside];
    startIn.alpha = 0;
    [welcomeScrollView addSubview:startIn];
    
    pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(0, startIn.origin.y  +20 , rect.size.width, 20)];
    pageControl.numberOfPages = 4;
    pageControl.tag = 101;
    pageControl.backgroundColor = [UIColor clearColor];
    //设置页码点的颜色
    pageControl.pageIndicatorTintColor = PNColor(196, 196, 196);
    //设置选中页码点的颜色
    pageControl.currentPageIndicatorTintColor = PNColor(52, 158, 247);
//    [pageControl sizeForNumberOfPages:2];
    [self.view addSubview:pageControl];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    int page = (scrollView.contentOffset.x)/scrollView.frame.size.width;
    if (page ==3) {
        
        [UIView animateWithDuration:0.5 animations:^{
            
             pageControl.hidden = YES;
             startIn.alpha = 1;
        }];
    }
    else
    {
        pageControl.hidden = NO;
        startIn.alpha = 0;
    }
    pageControl.currentPage = page;
    
}
-(void) initConfigFunction{
    self.indexTime=0;
    [AMapServices sharedServices].apiKey = mapKey;
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
}
-(void)viewWillAppear:(BOOL)animated{
    //清除消息通知数
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}
-(void) initViewFunction{
    self.view.backgroundColor = baseWelcomeSelectColor;
    
    [self.timeLabel setTextColor:[UIColor blackColor]];
    [self.timeLabel setBackgroundColor:[UIColor whiteColor]];
    self.timeLabel.text = [NSString stringWithFormat:@"%lds跳转",(long)self.indexTime];
    
    [[SINAUiviewClickLiserner alloc]viewClickFunction:self.timeLabel andWithBlick:^(UIView *view) {
        [self timeLabelClick];
    }];
    
    [self updateAppVersonFunction];
    //获取启动图片
    CGSize viewSize = KYRect.size;
    //横屏请设置成 @"Landscape"
    NSString *viewOrientation = @"Portrait";
    NSString *launchImageName = nil;
    NSArray* imagesDict = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"UILaunchImages"];
    for (NSDictionary* dict in imagesDict)
    {
        CGSize imageSize = CGSizeFromString(dict[@"UILaunchImageSize"]);
        if (CGSizeEqualToSize(imageSize, viewSize) && [viewOrientation isEqualToString:dict[@"UILaunchImageOrientation"]])
        {
            launchImageName = dict[@"UILaunchImageName"];
        }
    }
    UIImage * launchImage = [UIImage imageNamed:launchImageName];
    //将当前view的背景图设置为启动图片
    //self.view.backgroundColor = [UIColor colorWithPatternImage:launchImage];
    self.mainImageView.contentMode = UIViewContentModeScaleAspectFill;
    self.mainImageView.image = launchImage;
    
    if (@available(iOS 10.0, *)) { 
        NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
            [self repeatTimeFunction];
        }];
        self.timer = timer;
    } else {
        /**
         *
         *
         */
        
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(repeatTimeFunction) userInfo:nil repeats:true];
            [[NSRunLoop currentRunLoop] run];
            
        });
    }
    [self performSelector:@selector(toHomeFunction) withObject:nil afterDelay:3];
    
    self.appIconImageView.frame = CGRectMake(mainW/2-23, mainH/2-120, 46, 52);
    self.appIconLabel.frame = CGRectMake(mainW/2-30, CGRectGetMaxY(self.appIconImageView.frame)+16, 60, 20);
    self.appIconFlagLabel.frame = CGRectMake(mainW/2-41, CGRectGetMaxY(self.appIconLabel.frame)+10, 92, 22);
    
}
-(void)repeatTimeFunction{
    self.indexTime--;
    self.timeLabel.text = [NSString stringWithFormat:@"%lds跳转",(long)self.indexTime];
}
- (void)viewWillDisappear:(BOOL)animated{
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
}
//跳过
-(void)timeLabelClick{
    [self toHomeFunction];
}
- (UIStatusBarStyle)preferredStatusBarStyle {
    //    return UIStatusBarStyleLightContent;
    return UIStatusBarStyleLightContent;
}

-(void)onClickStartInButton:(id)sender
{
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:[NSNumber numberWithBool:YES] forKey:@"NOT_FIRST_START"];
    [userDefaults synchronize];
    
    NSLog(@"%@",welcomeScrollView.subviews);
    [welcomeScrollView removeFromSuperview];
    
    [self loadMainViewController];
}

-(void)loadMainViewController
{
    SINACommonUserHelper *userHepler =[SINACommonUserHelper share];
    SINAUserModel *userModel = [userHepler getUserModel];
    
    NSString *userId = nil;
    NSString *identitys = nil;
    
    if (userModel!=nil) {
        userId = userModel.userUid;
        identitys=userModel.identitys;
    }
    //用户身份标识  1学生  2教师 -1没有选择身份
    if (identitys==nil||[identitys isEqualToString:@"-1"]||userId==nil||[userId isEqualToString:@""]) {
        //登录页面
        SINALoginViewController *rootViewControll = [[SINALoginViewController alloc]init ];
        SINANavLoginViewController *homeController = [[SINANavLoginViewController alloc] initWithRootViewController:rootViewControll];
        [[SINAControllerUtils alloc]restoreRootViewController:homeController andWithWindow:self.view.window];
    } else {
        //用户身份标识  1学生  2教师 -1没有选择身份
        //home页面
        if ([identitys isEqualToString:@"1"]) {
            SINAStudentTabBarViewController *tabBarViewController = [[SINAStudentTabBarViewController alloc]init];
            AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
            app.tabVC = tabBarViewController;
            [[SINAControllerUtils alloc]restoreRootViewController:tabBarViewController andWithWindow:self.view.window];
        } else {
            SINATeacherTabBarViewController *tabBarViewController = [[SINATeacherTabBarViewController alloc]init];
            AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
            app.tabVC = tabBarViewController;
            [[SINAControllerUtils alloc]restoreRootViewController:tabBarViewController andWithWindow:self.view.window];
        }
    }
}

-(void) toHomeFunction{
    [self.timer invalidate];
    
    self.isTimeLoading = YES;
    
    if (self.isLoading) {
        return;
    }
    
    [self loadMainViewController];
    
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //设置全局状态栏字体颜色为黑色
    //    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    //设置全局状态栏字体颜色为白色
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    
    return YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
   
}
-(void) updateAppVersonFunction{
    
    self.isLoading = YES;
   
    [CXAFNHttpRequestUtils httpGetRequest:[NSString stringWithFormat:@"%@%@?platform=1",baseUrl,updateAppVersionUrl] success:^(id responseData) {
        NSString *code = responseData[@"code"];
    
        if ([code isEqualToString:@"1000"]) {
            NSDictionary *dictionary = responseData[@"content"];
            if (dictionary!=nil) {
                NSInteger versionCode = [dictionary[@"versionCode"] integerValue];
                if (versionCode>appVersionCode) {
                    //提示升级
                     self.isLoading = YES;
                    DLog(@"提示升级");
                   
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"升级提示" message:@"检测到有新的版本 请更新版本" preferredStyle:UIAlertControllerStyleAlert];
                  
                    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action) {
                       //跳转应用市场
                        //https://itunes.apple.com/cn/app/apple-store/id375380948?mt=8
                        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://itunes.apple.com/cn/app/id1398705717?mt=8"]];
                        
                        [[UIApplication sharedApplication] openURL:url];
                         [self exitApplication];
                    }];
                    UIAlertAction *cancelAction =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *_Nonnull action) {
                        //关闭
                        DLog(@"取消");
                        [self exitApplication];
                    }];
                    
                    [alert addAction:okAction];
                    [alert addAction:cancelAction];
                    
                    // 弹出对话框
                    [self presentViewController:alert animated:true completion:nil];
                } else {
                     DLog(@"不升级");
                    //不升级
                    self.isLoading = NO;
                    if (self.isTimeLoading) {
                        [self toHomeFunction];
                    }
                }
            }
            
        }else{
             self.isLoading = NO;
            if (self.isTimeLoading) {
                [self toHomeFunction];
            }
        }
       
      
        
    } failure:^(NSError *error, NSInteger errCode) {
         self.isLoading = NO;
        if (self.isTimeLoading) {
            [self toHomeFunction];
        }
    }];
    
}
- (void)exitApplication {
    //直接退，看起来好像是 crash 所以做个动画
    [UIView beginAnimations:@"exitApplication" context:nil];
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.view.window cache:NO];
    [UIView setAnimationDidStopSelector:@selector(animationFinished:finished:context:)];
    self.view.window.bounds = CGRectMake(0, 0, 0, 0);
    [UIView commitAnimations];
}

- (void)animationFinished:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
    if ([animationID compare:@"exitApplication"] == 0) {
        //退出代码
        exit(0);
    }
}
@end
